package com.yupi.springbootinit.utils;

import com.yupi.springbootinit.constant.AttachmentConstant;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 文件路径管理工具类
 * 提供完整的MES文件管理体系支持
 */
@Slf4j
public class FilePathUtils {

    /**
     * MES文件根目录
     */
    public static final String MES_ROOT_PATH = "D:" + File.separator + "MES_FILES";

    /**
     * 获取业务模块的中文名称
     */
    public static String getModuleChineseName(String bizType) {
        switch (bizType) {
            case AttachmentConstant.BizType.SALES_ORDER:
                return "销售订单";
            case AttachmentConstant.BizType.PROCESS_SHEET:
                return "工艺单";
            case AttachmentConstant.BizType.PRODUCTION_ORDER:
                return "生产订单";
            case AttachmentConstant.BizType.QUALITY_INSPECTION:
                return "质量检验";
            case AttachmentConstant.BizType.EQUIPMENT:
                return "设备管理";
            default:
                return "其他文件";
        }
    }

    /**
     * 获取文件分类的中文文件夹名称（带序号）
     */
    public static String getCategoryFolderName(String fileCategory) {
        switch (fileCategory) {
            // 销售订单相关
            case AttachmentConstant.FileCategory.CONTRACT:
                return "01_合同文件";
            case AttachmentConstant.FileCategory.CUSTOMER_DOC:
                return "02_客户资料";
            case AttachmentConstant.FileCategory.DRAWING:
                return "03_产品图纸";
            case AttachmentConstant.FileCategory.SPECIFICATION:
                return "04_规格说明";
            
            // 工艺单相关
            case AttachmentConstant.FileCategory.PROCESS_DOC:
                return "01_工艺文档";
            case AttachmentConstant.FileCategory.TOOLING_DRAWING:
                return "02_工装图纸";
            case AttachmentConstant.FileCategory.INSPECTION_DOC:
                return "03_检验文档";
            case AttachmentConstant.FileCategory.CHANGE_RECORD:
                return "04_变更记录";
            
            // 生产订单相关
            case AttachmentConstant.FileCategory.PRODUCTION_PLAN:
                return "01_生产计划";
            case AttachmentConstant.FileCategory.MATERIAL_LIST:
                return "02_物料清单";
            case AttachmentConstant.FileCategory.PRODUCTION_RECORD:
                return "03_生产记录";
            case AttachmentConstant.FileCategory.QUALITY_RECORD:
                return "04_质量记录";
            
            // 质量检验相关
            case AttachmentConstant.FileCategory.QUALITY_DOC:
                return "01_质量文档";
            case AttachmentConstant.FileCategory.INSPECTION_REPORT:
                return "02_检验报告";
            case AttachmentConstant.FileCategory.CERTIFICATE:
                return "03_证书文件";
            case AttachmentConstant.FileCategory.TEST_REPORT:
                return "04_测试报告";
            
            // 设备管理相关
            case AttachmentConstant.FileCategory.EQUIPMENT_DOC:
                return "01_设备文档";
            case AttachmentConstant.FileCategory.MAINTENANCE_RECORD:
                return "02_维护记录";
            case AttachmentConstant.FileCategory.FAULT_RECORD:
                return "03_故障记录";
            
            // 其他
            case AttachmentConstant.FileCategory.OTHER:
                return "99_其他文件";
            
            default:
                return "99_未分类文件";
        }
    }

    /**
     * 生成子业务编码
     */
    public static String generateSubBizCode(String bizType, Long bizId, String suffix) {
        String prefix;
        switch (bizType) {
            case AttachmentConstant.BizType.PROCESS_SHEET:
                prefix = "PS";
                break;
            case AttachmentConstant.BizType.PRODUCTION_ORDER:
                prefix = "PO";
                break;
            case AttachmentConstant.BizType.QUALITY_INSPECTION:
                prefix = "QI";
                break;
            default:
                prefix = "BIZ";
                break;
        }
        return prefix + String.format("%03d", bizId % 1000) + "_" + suffix;
    }

    /**
     * 创建目录（如果不存在）
     */
    public static boolean createDirectoryIfNotExists(String path) {
        try {
            File directory = new File(path);
            if (!directory.exists()) {
                boolean created = directory.mkdirs();
                if (created) {
                    log.info("成功创建目录: {}", path);
                } else {
                    log.warn("创建目录失败: {}", path);
                }
                return created;
            }
            return true;
        } catch (Exception e) {
            log.error("创建目录异常: {}", path, e);
            return false;
        }
    }

    /**
     * 获取文件的相对路径（用于数据库存储）
     */
    public static String getRelativePath(String fullPath) {
        if (fullPath.startsWith(MES_ROOT_PATH)) {
            return fullPath.substring(MES_ROOT_PATH.length());
        }
        return fullPath;
    }

    /**
     * 获取文件的完整路径
     */
    public static String getFullPath(String relativePath) {
        if (relativePath.startsWith(MES_ROOT_PATH)) {
            return relativePath;
        }
        return MES_ROOT_PATH + relativePath;
    }

    /**
     * 生成带时间戳的文件名
     */
    public static String generateTimestampFileName(String originalFileName) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String extension = getFileExtension(originalFileName);
        String nameWithoutExtension = getFileNameWithoutExtension(originalFileName);
        
        return nameWithoutExtension + "_" + timestamp + 
               (extension.isEmpty() ? "" : "." + extension);
    }

    /**
     * 获取文件扩展名
     */
    public static String getFileExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "";
        }
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex == -1 || lastDotIndex == fileName.length() - 1) {
            return "";
        }
        return fileName.substring(lastDotIndex + 1).toLowerCase();
    }

    /**
     * 获取不带扩展名的文件名
     */
    public static String getFileNameWithoutExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "";
        }
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex == -1) {
            return fileName;
        }
        return fileName.substring(0, lastDotIndex);
    }
}